from flask import Blueprint, request

from config import DAY_S
from db_init import db
from model.model import *
from tools.tools import my_route
from model import model
import arrow

back = Blueprint('back', __name__)


# 添加房屋信息
@back.route('/add_house', methods=['POST'])
def add_house():
    data = request.form
    db.session.add(House(**data))
    db.session.commit()
    return my_route(200)


# 删除房屋信息
@back.route('/delete_house/<int:hid>', methods=['DELETE'])
def delete_house(hid):
    House.query.filter_by(id=hid).delete()
    db.session.commit()
    return my_route(200)


# 修改
@back.route('/<url_table>/<int:hid>', methods=['PUT'])
def put_house(url_table, hid):
    table = url_table.title()
    data = request.form
    if hasattr(model, table):
        getattr(model, table).query.filter_by(id=hid).update(data)
    else:
        return {'msg': 'url不对', 'code': 404, 'data': data}
    db.session.commit()
    return my_route(200)


@back.route('/statistics/occupancy', methods=['GET'])
def occupancy():
    year_now = arrow.now().year
    start_t = arrow.get(f'{year_now}-01-01 00:00:00', 'YYYY-MM-DD HH:mm:ss')
    end_t = arrow.get(f'{year_now}-12-31 24:00:00', 'YYYY-MM-DD HH:mm:ss')
    interval = end_t - start_t
    total = House.query.count() * interval.days
    orders = Order.query.filter(Order.start_t < end_t.int_timestamp, Order.end_t > start_t.int_timestamp).all()
    days = 0
    for order in orders:
        days += (order.end_t - order.start_t) // DAY_S
    return '%.3f' % (days*100 / total) + '%'
